package com.smasher.widget.base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.ActionMenuView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.WindowCompat;

import com.smasher.widget.R;
import com.smasher.widget.activityoptions.SmasherActivityManager;
import com.smasher.widget.other.BusProvider;
import com.smasher.widget.other.Saturation;

import java.lang.reflect.Method;


/**
 * @author matao
 * @version 2.1.1
 */
public abstract class BaseActivity extends AppCompatActivity {

    private static final String TAG = "BaseActivity";

    protected View mRoot;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 添加到Activity工具类
        SmasherActivityManager.getInstance().addActivity(this);

        Intent intent = getIntent();
        Bundle bundle = null;
        if (intent != null) {
            bundle = intent.getExtras();
        }

        initParams(bundle);

        mRoot = getRootView();
        setContentView(mRoot);

        //设置灰度
        initSaturation();
        BusProvider.getInstance().register(this);
        initView();
        initData();
    }

    private void initSaturation() {
        setMonochrome(Saturation.getInstance().getSaturation());
    }

    private void logScreenSize() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int densityDpi = dm.densityDpi;
        int widthPixels = dm.widthPixels;
        int heightPixels = dm.heightPixels;
        Log.e(TAG, "==================================================");
        Log.e(TAG, "densityDpi=" + densityDpi);
        Log.e(TAG, "widthPixels=" + widthPixels);
        Log.e(TAG, "heightPixels=" + heightPixels);
        Log.e(TAG, "==================================================");
    }

    /**
     * 适配全屏
     */
    private void settingFullScreen() {
        WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
    }

    /**
     * 适配 刘海屏、开口屏
     */
    private void settingCutPlayMode() {
        Window window = getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            WindowManager.LayoutParams lp = window.getAttributes();

            // 仅当缺口区域完全包含在状态栏之中时，才允许窗口延伸到刘海区域显示//
            //lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT;
            // 永远不允许窗口延伸到刘海区域//
            //lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER;
            //允许window 的内容可以上移到刘海屏状态栏
            lp.layoutInDisplayCutoutMode =
                    WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
            window.setAttributes(lp);
        }
    }

    /**
     * 黑白化 设置饱和度
     */
    protected void setMonochrome(float saturation) {
        Paint paint = new Paint();
        ColorMatrix colorMatrix = new ColorMatrix();
        colorMatrix.setSaturation(saturation);
        paint.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
        getWindow().getDecorView().setLayerType(View.LAYER_TYPE_HARDWARE, paint);
    }

    @Override
    protected void onDestroy() {
        SmasherActivityManager.getInstance().removeActivity(this);
        BusProvider.getInstance().unregister(this);
        super.onDestroy();
        Log.d(TAG, "onDestroy: " + this.getClass());
    }

    @Override
    public void finish() {
        super.finish();
        Log.d(TAG, "finish: " + this.getClass());
        overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
    }


    /**
     * 获取传递信息
     *
     * @param bundle bundle
     */
    public void initParams(Bundle bundle) {

    }

    /**
     * 进行获取根部的View
     *
     * @return RootView
     */
    public abstract View getRootView();

    /**
     * 进行初始化相关的View
     */
    public abstract void initView();

    /**
     * 进行初始化相关的数据
     */
    public abstract void initData();


    /**
     * 获取是否存在NavigationBar
     * HUAWEI
     *
     * @param context context
     * @return boolean
     */
    @SuppressLint("PrivateApi")
    @SuppressWarnings("unchecked")
    public boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                //不存在虚拟按键
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                //存在虚拟按键
                hasNavigationBar = true;
            }
        } catch (Exception e) {
            Log.e(TAG, "checkDeviceHasNavigationBar: ", e);
        }
        return hasNavigationBar;
    }


    private TextView mTitleView = null;

    /**
     * 设置Toolbar Title 居中
     *
     * @param toolbar toolbar
     */
    public void setTitleCenter(Toolbar toolbar) {
        if (toolbar == null) {
            return;
        }
        String title = "loong_title";
        CharSequence titleSequence = toolbar.getTitle();
        String originalTitle = titleSequence != null ? titleSequence.toString() : "";
        toolbar.setTitle(title);
        toolbar.setLogo(null);
        for (int i = 0; i < toolbar.getChildCount(); i++) {
            View view = toolbar.getChildAt(i);

            if (view instanceof ImageButton navigation) {
                Log.i(TAG, "ImageButton: ");
                //  布局发生改变的时候拿到导航的宽度
                //  因为标题设置居中的时候会偏向右边
                navigation.addOnLayoutChangeListener(onNavigationLayoutChangeListener);
            }

            if (view instanceof ActionMenuView menuView) {
                Log.i(TAG, "menuView: ");
                menuView.addOnLayoutChangeListener(onMenuLayoutChangeListener);
            }

            if (view instanceof TextView target) {
                if (target.getText().equals(title)) {
                    mTitleView = target;
                    target.setGravity(Gravity.CENTER);
                    target.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
                }
            }
        }
        toolbar.setTitle(originalTitle);
    }

    private final View.OnLayoutChangeListener onNavigationLayoutChangeListener = (v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
        if (mTitleView != null) {
            //  把标题的右边也进行一个padding 导航的宽度，让标题显得在整个屏幕中间
            int paddingLeft = mTitleView.getPaddingLeft();
            int paddingRight = mTitleView.getPaddingRight();
            int rightGap = v != null ? v.getWidth() : 0;
            mTitleView.setPadding(paddingLeft, 0, rightGap + paddingRight, 0);
        }
    };

    private final View.OnLayoutChangeListener onMenuLayoutChangeListener = (v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
        if (mTitleView != null) {
            //  把标题的右边也进行一个padding 导航的宽度，让标题显得在整个屏幕中间
            int paddingLeft = mTitleView.getPaddingLeft();
            int paddingRight = mTitleView.getPaddingRight();
            int rightGap = v != null ? v.getWidth() : 0;
            mTitleView.setPadding(paddingLeft + rightGap, 0, paddingRight, 0);
        }
    };

}
